<template>
  <div class="app-container">

    <el-button type="primary" style="margin-bottom: 20px;" icon="Search" @click="getList('1')">获取最新数据</el-button>

    <el-table :summary-method="getSummaries" border show-summary style="padding: 0px;margin: 0px;" v-loading="loading"
      :data="costingList" @selection-change="handleSelectionChange">
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="申请人" width="100" align="center" prop="name" />
      <el-table-column label="报销日期" align="center" prop="submitDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.submitDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总费用" width="150" align="center" prop="total" />
      <!-- <el-table-column label="报销类型" align="center" prop="useType" /> -->

      <el-table-column label="备注" align="center" show-overflow-tooltip prop="remark" />
    </el-table>

    <!-- <pagination style="margin-right: 0px; float: right;" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" /> -->
    <!-- 添加或修改正式清单的商品对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="costingRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="备注编码" prop="housekeeperProject">
          <el-select @change="setRemarkCode" clearable v-model="form.goodsId" filterable placeholder="请选择或输入关键字查找"
            style="width: 240px">
            <el-option v-for="item in saleList" :key="item.goodsId" :label="item.goodsAllName" :value="item.goodsId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Costing">
import { listCosting, getCosting, delCosting, addCosting, updateCosting } from "@/api/project/costing";
import { listSale, getSale, delSale, addSale, updateSale, gjpListSale, gjpAllListSale } from "@/api/project/sale";
import { Bell } from '@element-plus/icons-vue'
import { listFee, getFee, delFee, addFee, updateFee } from "@/api/project/fee";
const props = defineProps({
  datas: {
    type: Object, // 指定类型为对象
    required: true, // 是否必填
  },
  column: {
    type: Number, // 指定类型为数字
    default: 3, // 设置默认值为 3
  },
  sizes: {
    default: 'default',
  },
  personList: {
    default: [],
  },
  payList: {
    default: [],
  },
  attachmentList: {
    default: [],
  },
  implementList: {
    default: [],
  },
  warrantyList: {
    default: [],
  },
  accountingList: {
    default: [],
  },


  isView: {
    default: false,
  },


});
const { datas, column, sizes, personList, payList, attachmentList, implementList, accountingList, warrantyList, isView } = toRefs(props);

const { proxy } = getCurrentInstance();

const costingList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const saleList = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    name: null,
    model: null,
    param: null,
    brand: null,
    count: null,
    unit: null,
    price: null,
    totalPrice: null,
    discountRate: null,
    discountPrice: null,
    remarkCode: null,
    preCount: null,
    prePrice: null,
    preUnit: null,
    finalCount: null,
    finalCost: null,
    loginIp: null,
    loginDate: null,
    projectNo: null,
    goodsId: null
  },
  rules: {
    id: [
      { required: true, message: "id不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询正式清单的商品列表 */
function getList(type) {
  loading.value = true;
  queryParams.value.projectNo = datas.value.projectNo
  queryParams.value.refresh = type
  console.log("费用汇总", queryParams.value);
  listFee(queryParams.value).then(response => {
    costingList.value = response.data;
    console.log("fffffffffffff", response.data);
    loading.value = false;
  });

  // listSale(params).then(response => {
  //     //获取管家婆项目对应的出库数据

  // });


}


// 行样式方法
const tableRowClassName = ({ row }) => {
  return row.status == 1 ? 'warning-row' : '';
};


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    model: null,
    param: null,
    brand: null,
    count: null,
    unit: null,
    price: null,
    totalPrice: null,
    discountRate: null,
    discountPrice: null,
    remarkCode: null,
    preCount: null,
    prePrice: null,
    preUnit: null,
    finalCount: null,
    finalCost: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
    loginIp: null,
    loginDate: null,
    projectNo: null
  };
  proxy.resetForm("costingRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList("0");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加正式清单的商品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  let params = {
    housekeeperProject: datas.value.housekeeperProject
  }

  if (!params.housekeeperProject) {
    proxy.$modal.msgError("未关联管家婆项目,请先关联");
    loading.value = false;
    return
  }
  console.log("params.housekeeperProject", params.housekeeperProject);

  gjpAllListSale(params).then(response => {
    console.log('所有出库单', response);
    saleList.value = response.data;
  });


  const _id = row.id || ids.value
  getCosting(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "选择实际对应的出库数据";
  });


}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["costingRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCosting(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList("0");
        });
      } else {
        addCosting(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList("0");
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除正式清单的商品编号为"' + _ids + '"的数据项？').then(function () {
    return delCosting(_ids);
  }).then(() => {
    getList("0");
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

function getSummaries(param) {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = `合计（共 ${data.length} 条）`;
      return;
    }

    const prop = column.property;

    // 需要统计的列配置
    const statsColumns = {
      total: { name: '报销合计', format: 'money' },
    };

    if (statsColumns[prop]) {
      const values = data.map(item => Number(item[prop]));
      if (!values.every(value => isNaN(value))) {
        const sum = values.reduce((prev, curr) => {
          const value = Number(curr);
          return isNaN(value) ? prev : prev + value;
        }, 0);

        // 格式化输出
        switch (statsColumns[prop].format) {
          case 'int':
            sums[index] = Math.round(sum);
            break;
          case 'money':
            sums[index] = sum.toFixed(2);
            break;
          default:
            sums[index] = sum;
        }
        sums[index] = "￥ " + sums[index]
      } else {
        sums[index] = 'N/A';
      }
    } else {
      sums[index] = '';
    }
  });

  return sums;
}


const setRemarkCode = (id) => {
  if (id == undefined) {
    form.value.remarkCode = '';
    return
  }
  const filteredObjects = saleList.value.find((obj) => obj.goodsId == id);
  form.value.remarkCode = '';
  console.log("filteredObjects", filteredObjects);
  form.value.remarkCode = filteredObjects?.goodsAllName || '';
  console.log("setHousekeeperName", form.value.remarkCode);
}


onMounted(() => {
  // nextTick(() => {
  console.log("当前", datas);
  getList("0")
  // })
})
</script>


<style scoped>
:deep(.el-table .warning-row) {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

/* 悬停效果 */
:deep(.el-table .warning-row:hover td) {
  --el-table-tr-bg-color: var(--el-color-warning-light-8);
  background-color: var(--el-table-tr-bg-color);
}

/* 如果需要更醒目的边框样式 */
:deep(.el-table .warning-row td) {
  border-bottom: 1px solid var(--el-color-warning-light-5);
  border-top: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:first-child) {
  border-left: 1px solid var(--el-color-warning-light-5);
}

:deep(.el-table .warning-row td:last-child) {
  border-right: 1px solid var(--el-color-warning-light-5);
}
</style>